/**
 * 贪吃蛇游戏核心逻辑模块
 */
 class SnakeGame {
    constructor(canvasWidth, canvasHeight, gridSize = 20) {
      this.canvasWidth = canvasWidth;
      this.canvasHeight = canvasHeight;
      this.gridSize = gridSize;
      
      // 游戏状态
      this.state = {
        gameState: 'ready', // ready, running, paused, over
        score: 0,
        highScore: this.loadHighScore(),
        speed: 100, // 毫秒每格
        direction: 'right',
        nextDirection: 'right',
        lastUpdateTime: 0
      };
      
      // 蛇体数据
      this.snake = [];
      this.initializeSnake();
      
      // 食物数据
      this.food = this.generateFood();
    }
    
    // 初始化蛇体
    initializeSnake() {
      const startX = Math.floor(this.canvasWidth / 2 / this.gridSize) * this.gridSize;
      const startY = Math.floor(this.canvasHeight / 2 / this.gridSize) * this.gridSize;
      
      this.snake = [
        { x: startX, y: startY },
        { x: startX - this.gridSize, y: startY },
        { x: startX - this.gridSize * 2, y: startY }
      ];
    }
    
    // 生成食物
    generateFood() {
      const maxX = Math.floor(this.canvasWidth / this.gridSize) - 1;
      const maxY = Math.floor(this.canvasHeight / this.gridSize) - 1;
      
      let food;
      let isOnSnake;
      
      do {
        food = {
          x: Math.floor(Math.random() * maxX) * this.gridSize,
          y: Math.floor(Math.random() * maxY) * this.gridSize
        };
        
        isOnSnake = this.snake.some(segment => 
          segment.x === food.x && segment.y === food.y
        );
      } while (isOnSnake);
      
      return food;
    }
    
    // 更新游戏状态
    update(currentTime) {
      if (this.state.gameState !== 'running') return;
      
      // 控制蛇的移动速度
      if (currentTime - this.state.lastUpdateTime < this.state.speed) return;
      this.state.lastUpdateTime = currentTime;
      
      // 应用方向改变
      this.state.direction = this.state.nextDirection;
      
      // 移动蛇
      const head = { ...this.snake[0] };
      
      switch (this.state.direction) {
        case 'up':
          head.y -= this.gridSize;
          break;
        case 'down':
          head.y += this.gridSize;
          break;
        case 'left':
          head.x -= this.gridSize;
          break;
        case 'right':
          head.x += this.gridSize;
          break;
      }
      
      // 检查碰撞
      if (this.checkCollision(head)) {
        this.gameOver();
        return;
      }
      
      // 移动蛇体
      this.snake.unshift(head);
      
      // 检查是否吃到食物
      if (head.x === this.food.x && head.y === this.food.y) {
        this.state.score += 10;
        if (this.state.score > this.state.highScore) {
          this.state.highScore = this.state.score;
          this.saveHighScore();
        }
        this.food = this.generateFood();
      } else {
        this.snake.pop();
      }
    }
    
    // 检查碰撞
    checkCollision(head) {
      // 边界检查
      if (
        head.x < 0 ||
        head.y < 0 ||
        head.x >= this.canvasWidth ||
        head.y >= this.canvasHeight
      ) {
        return true;
      }
      
      // 自身碰撞检查
      return this.snake.some(segment => segment.x === head.x && segment.y === head.y);
    }
    
    // 改变方向
    changeDirection(newDirection) {
      // 防止180度转弯
      if (
        (this.state.direction === 'up' && newDirection === 'down') ||
        (this.state.direction === 'down' && newDirection === 'up') ||
        (this.state.direction === 'left' && newDirection === 'right') ||
        (this.state.direction === 'right' && newDirection === 'left')
      ) {
        return;
      }
      
      this.state.nextDirection = newDirection;
    }
    
    // 开始游戏
    startGame() {
      if (this.state.gameState === 'ready' || this.state.gameState === 'over') {
        this.state.gameState = 'running';
        this.state.score = 0;
        this.initializeSnake();
        this.state.direction = 'right';
        this.state.nextDirection = 'right';
        this.food = this.generateFood();
      } else if (this.state.gameState === 'paused') {
        this.state.gameState = 'running';
      }
    }
    
    // 暂停游戏
    togglePause() {
      if (this.state.gameState === 'running') {
        this.state.gameState = 'paused';
      } else if (this.state.gameState === 'paused') {
        this.state.gameState = 'running';
      }
    }
    
    // 游戏结束
    gameOver() {
      this.state.gameState = 'over';
    }
    
    // 加载最高分
    loadHighScore() {
      return parseInt(localStorage.getItem('snakeHighScore')) || 0;
    }
    
    // 保存最高分
    saveHighScore() {
      localStorage.setItem('snakeHighScore', this.state.highScore.toString());
    }
    
    // 获取游戏状态
    getGameState() {
      return this.state;
    }
    
    // 获取蛇体数据
    getSnake() {
      return this.snake;
    }
    
    // 获取食物数据
    getFood() {
      return this.food;
    }
  }